package com.xjlsoft.weather.controller;

import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xjlsoft.weather.dto.AerosolDataListDto;
import com.xjlsoft.weather.dto.ExportResponseDto;
import com.xjlsoft.weather.dto.ExportDto;
import com.xjlsoft.weather.dto.PageDto;
import com.xjlsoft.weather.dto.ResultEntity;
import com.xjlsoft.weather.dto.WeatherDataQueryDto;
import com.xjlsoft.weather.entity.AerosolData;
import com.xjlsoft.weather.entity.AerosolDataExcelDto;
import com.xjlsoft.weather.entity.GroundDataExcelDto;
import com.xjlsoft.weather.enums.ResultCodeEnum;
import com.xjlsoft.weather.service.AerosolDataExcelDtoService;
import com.xjlsoft.weather.service.AerosolDataService;
import com.xjlsoft.weather.util.ResultUtil;
import com.xjlsoft.weather.util.WeatherDataUtil;
import com.xjlsoft.weather.mapper.AerosolDataExcelDtoMapper;
import com.xjlsoft.weather.mapper.AerosolDataMapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/aerosol")
@Api(tags = "气溶胶 数据接口")
public class AerosolDataController {
	
	
	private static final Logger logger = LoggerFactory.getLogger(AerosolDataController.class);
	
	@Autowired
	private AerosolDataMapper aerosolDataMapper;
	
	@Autowired
	private AerosolDataService aerosolDataService;
	
	@Autowired
	private AerosolDataExcelDtoService aerosolDataExcelDtoService;
   
	
	@Value("${excelfilePortPrefix}")
	private String excelfilePortPrefix;

	@Value("${excelfileUri}")
	private String excelfileUri;
	/**
	 * 按条件查询地面数据接口  <br/>
	 * json格式 传递参数
	 * @param WeatherDataQueryDto 查询参数
	 * @throws ParseException 
	 * 
	 * */
   @ApiOperation(value="按条件  分页查询   气溶胶数据 接口",notes="分页查询 气溶胶数据 ")
   @RequestMapping(value="/getAerosolDataByDto" ,method=RequestMethod.POST)
   public ResultEntity getAerosolDataByDto(@RequestBody WeatherDataQueryDto weatherDataQueryDto) throws ParseException{
	   
	   PageDto pageDto=new PageDto();
	   pageDto.setSize(weatherDataQueryDto.getSize());
	   pageDto.setCurrent(weatherDataQueryDto.getCurrent());
	   
	   WeatherDataQueryDto weatherDataDto=weatherDataQueryDto;
       IPage<AerosolDataListDto> userIPage = aerosolDataService.getList(pageDto, weatherDataDto);
	   //IPage<GroundDataListDto> data= groundDataService.getList(page, weatherDataQueryDto);
       ResultEntity result=new ResultEntity(ResultCodeEnum.SUCCESS,userIPage,true);
       //Map<String, Object> map=ResultUtil.resultMap(result);
       return result;
   };
   
   
   /**
	 * 根据id 查询 气溶胶数据  <br/>
	 * 
	 * @param WeatherDataQueryDto 查询参数
	 * 
	 * */
  @ApiOperation(value="根据id 查询 气溶胶数据",notes="查询 气溶胶,返回地面数据全部值")
  @ApiImplicitParams({
		@ApiImplicitParam(name="aeroso_id",value="气溶胶 数据id",required=true,paramType="query",dataType="String")
	})
  @RequestMapping(value="/getAerosolDataById" ,method=RequestMethod.POST)
  public Object getAerosolDataById(@RequestParam(value="aeroso_id",required = true) String aeroso_id){
	   
	  AerosolData ad =aerosolDataMapper.selectById(aeroso_id);
	  ResultEntity result=null;
	  if(ad!=null){
		  result =new ResultEntity(ResultCodeEnum.SUCCESS,ad,true);
	  }else{
		  result=new ResultEntity(ResultCodeEnum.FAILURE,null,false);
	  }
      
      Map<String, Object> map=ResultUtil.resultMap(result);
      return map;
  }
  
  

/**
 * 
 * 可能抛出的异常  IOException
* @throws Exception 
 * 
 * */
@ApiOperation(value = "动态导出excel", notes = "根据前台传入的 查询列，与字段含义,动态查询数据并导出，请确保列数 =字段含义数   <br> 例子：{\"dateEnd\":\"2020-03-03 00:00:00\",\"dateStart\":\"2020-03-01 00:00:00\",\"selectFilds\":\"ground_data_id,data_query_id,create_time,data_time\",\"selectUnits\":\"数据id,查询id,创建时间,数据时间\"}"
, produces = "application/json")
@RequestMapping(value = "/export", method = RequestMethod.POST)
public Object exporAerosolData(@RequestBody ExportDto exportDto) throws Exception {
	String filename = exportDto.getDateStart().replace(":", "") + "-" + exportDto.getDateEnd().replace(":", "");
	
	filename = filename.replace(" ", "");
	
	
	String path = excelfilePortPrefix + File.separator + this.excelfileUri + File.separator + filename;
	

	if ("true".equals(exportDto.getExportAllFlag())) {
		List<AerosolDataExcelDto> list = aerosolDataExcelDtoService.getList(exportDto);
		// String filename="地面数据导出";
		String suffix="气溶胶数据全部字段导出.xlsx";
		File file = new File(path+ suffix);
		boolean flag=WeatherDataUtil.writeExcel(list, file, "气溶胶数据", AerosolDataExcelDto.class);
		ResultEntity result = null;
		ExportResponseDto dto = new ExportResponseDto();
		
		if (flag) {
			//返回  访问静态文件的 后缀地址  前缀地址 前端来处理
			String excelUrl = this.excelfileUri + "/" + filename+suffix;
			dto.setFilepath(excelUrl);
			result = new ResultEntity(ResultCodeEnum.SUCCESS, dto, true);
		} else {
			result = new ResultEntity(ResultCodeEnum.FAILURE, null, false);
		}
		return result;
	}
	
	

	// 导出文件的名字
	// String filename="地面数据导出";
	// 工作簿名称
	String sheetName = "气溶胶数据";
	// 所有行数据，每一行其实就是一个封装的实体对象
	List<Map<String, Object>> listMap = aerosolDataExcelDtoService.getListMap(exportDto);

	String untis = exportDto.getSelectUnits();
	// 标题集合
	List<String> untisList = WeatherDataUtil.strToArrayList(untis);
	Iterator<String> iteru = untisList.iterator();

	String fileds = exportDto.getSelectFilds();
	// 查询字段集合
	List<String> filedsList = WeatherDataUtil.strToArrayList(fileds);
	// Iterator<String> iterf=filedsList.iterator();

	List<ArrayList<Object>> listdata = new ArrayList<ArrayList<Object>>();

	Iterator<Map<String, Object>> iter = listMap.iterator();

	// 循环处理 值
	while (iter.hasNext()) {
		Map<String, Object> mp = iter.next();
		Iterator<String> iterf = filedsList.iterator();
		ArrayList<Object> data = new ArrayList<Object>();
		while (iterf.hasNext()) {
			String str = iterf.next();
			data.add(mp.get(str));
		}
		listdata.add(data);
	}

	// 循环创建 标题
	List<List<String>> headList = new ArrayList<>();
	while (iteru.hasNext()) {
		String str = iteru.next();
		List<String> head = new ArrayList<>();
		head.add(str);
		headList.add(head);
	}
	ResultEntity result = null;

	try {
		String suffix="气溶胶数据部分字段导出.xlsx";
		File file = new File(path+ suffix);
		boolean flag = WeatherDataUtil.writeDynamicHeadExcel(listdata, file, sheetName, GroundDataExcelDto.class,headList);
		ExportResponseDto dto = new ExportResponseDto();
		
		if (flag) {
			//返回  访问静态文件的 后缀地址  前缀地址 前端来处理
			String excelUrl = this.excelfileUri + "/" + filename+suffix;
			dto.setFilepath(excelUrl);
			result = new ResultEntity(ResultCodeEnum.SUCCESS, dto, true);
		} else {
			result = new ResultEntity(ResultCodeEnum.FAILURE, null, false);
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return result;  
	
}    
    /**
     * 
     * 可能抛出的异常  IOException
   * @throws Exception 
     * 
     * */
    @ApiOperation(value = "查询动态导出excel的行数", notes = "请传入 查询条件  例子：{\"dateEnd\":\"2020-03-03 00:00:00\",\"dateStart\":\"2020-03-01 00:00:00\"}", produces = "application/json")
    @RequestMapping(value = "/exportCount", method = RequestMethod.POST)
    public Object exportAerosolDataCount(@RequestBody ExportDto exportDto) throws Exception{
  	
       
        int count=aerosolDataService.getListMapCount(exportDto);
        
       
        
        ResultEntity result=null;
  	  if(count>0){
  		  ExportResponseDto ed=new ExportResponseDto();
  		  ed.setCount(count);
  		  result =new ResultEntity(ResultCodeEnum.SUCCESS,ed,true);
  	  }else{
  		  result=new ResultEntity(ResultCodeEnum.FAILURE,null,false);
  	  }
        
        Map<String, Object> map=ResultUtil.resultMap(result);
        return map;
       
  	}    

   
   
   
   

}
